package com.inspur.sc.springboot.utils;

import com.inspur.sc.springboot.vo.UploadFileVO;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class UploadUtil {

    /**
     * 文件上传，并返回文件信息
     * @param multipartHttpServletRequest
     * @return
     */
    public static List<UploadFileVO> getUploadFiles(MultipartHttpServletRequest multipartHttpServletRequest) {

        List<MultipartFile> files = multipartHttpServletRequest.getFiles("files");
        List<UploadFileVO> fileList = new ArrayList<>();
        for (MultipartFile file : files) {
            // 取得上传文件
            String fileName = file.getOriginalFilename();
            Long fileSize = file.getSize();
            if (null != fileName && !"".equals(fileName)) {
                try {
                    // 获取文件类型
                    String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                    String id = UUID.randomUUID().toString();
                    String targetName = id + "." + fileType;
                    // 文件真实存放路径
                    String filePath = targetName;
                    // 保存文件
                    file.transferTo(new File(filePath));
                    // 初始化上传文件
                    UploadFileVO up = new UploadFileVO(fileName, fileType, fileSize + "", filePath);
                    fileList.add(up);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return fileList;
    }
}
